/**
 * Project Name:mauto-web
 * File Name:BaseController.java
 * Package Name:com.inftech.mauto.common.base
 * Date:2016年10月8日上午10:56:34
 * Copyright (c) 2016, inf-technology Co., Ltd. All Rights Reserved.
 *
*/

package com.inftech.mauto.common.base;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ExceptionHandler;

import com.alibaba.fastjson.JSONObject;
import com.inftech.mauto.common.constant.HttpStatusCodeEnum;
import com.inftech.mauto.sys.entity.ResultJson;
import com.mingsoft.base.constant.e.BaseEnum;
import com.mingsoft.basic.action.BaseAction;

/**
 * ClassName:BaseController <br/>
 * Function: 控制器支持类. <br/>
 * Date: 2016年10月8日 上午10:56:34 <br/>
 * 
 * @author jeno
 * @version
 * @since JDK 1.7
 */
public class BaseController extends BaseAction {

	/**
	 * 
	 * getOutJson:返回json字符串. <br/>
	 *
	 * @author puyf
	 * @param code
	 * @param flag
	 * @param msg
	 * @param data
	 * @return
	 * @since JDK 1.7
	 */
	protected String getOutJson(BaseEnum code, boolean flag, String msg, Object data) {
		ResultJson result = new ResultJson();
		if (code != null) {
			result.setCode(String.valueOf(code.toInt()));
		}
		result.setResult(flag);
		result.setResultMsg(msg);
		result.setResultData(data);
		net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
		return jsonObject.toString();
	}
	
	protected String getOutJson1(BaseEnum code, boolean flag, String msg, Object data) {
		ResultJson result = new ResultJson();
		if (code != null) {
			result.setCode(String.valueOf(code.toInt()));
		}
		result.setResult(flag);
		result.setResultMsg(msg);
		if(data==null){
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("code", String.valueOf(code.toInt()));
			map.put("result", flag);
			map.put("resultMsg", msg);
			net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(map);
			return jsonObject.toString();
		}
		result.setResultData(data);
		net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
		return jsonObject.toString();
	}

	/**
	 * 业务层执行异常处理
	 */
	@ExceptionHandler({ BusinessException.class })
	public void businessException(HttpServletRequest request, Exception ex, HttpServletResponse response) {
		BusinessException e = (BusinessException) ex;
		HttpStatusCodeEnum statusCode = e.getHttpStatusCodeEnum();
		String res = getOutJson(e.getHttpStatusCodeEnum(), false, statusCode.toString(), null);
		try {
			response.reset();
			response.setContentType("application/json");
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(res);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}

	}

}
